package com.zzw.basic.io.nio;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    private static Selector                selector;
    private static ServerSocketChannel     server;
    private final int                      port       = 8080;
    private Charset                        charset    = Charset.forName("UTF-8");
    private ByteBuffer                     rcBuffer   = ByteBuffer.allocate(1024);
    private ByteBuffer                     sendBuffer = ByteBuffer.allocate(1024);
    private HashMap<SocketChannel, String> data       = new HashMap<>();

    public NIOServer() throws IOException {
        selector = Selector.open();
        server   = ServerSocketChannel.open();
        server.socket().bind(new InetSocketAddress(port));
        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("NIOServer初始化完成");
    }

    public void listen() throws IOException {
        while (true) {
            int select = selector.select(3000);    // 加个超时

            if (select < 0) {
                continue;
            }

            Set<SelectionKey>      selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator      = selectionKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();

                process(key);
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new NIOServer().listen();
    }

    public void process(SelectionKey key) {
        SocketChannel channel = null;

        try {
            if (key.isValid() && key.isAcceptable()) {
                channel = server.accept();
                channel.configureBlocking(false);
                channel.register(selector, SelectionKey.OP_READ);
            } else if (key.isValid() && key.isReadable()) {
                channel = (SocketChannel) key.channel();
                rcBuffer.clear();

                int len = channel.read(rcBuffer);

                if (len > 0) {
                    String msg = new String(rcBuffer.array(), 0, len);

                    System.out.println("收到:" + msg);
                    channel.register(selector, SelectionKey.OP_WRITE);
                    data.put(channel, msg);
                }
            } else if (key.isValid() && key.isWritable()) {
                sendBuffer.clear();
                channel = (SocketChannel) key.channel();
                sendBuffer.put(new String(data.get(channel)).getBytes());
                sendBuffer.flip();    // 设置读取位
                channel.write(sendBuffer);
                channel.register(selector, SelectionKey.OP_READ);
            }
        } catch (Exception e) {
            e.printStackTrace();
            key.cancel();

            try {
                channel.socket().close();
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
